<template>
  <div class="tab-bbar d-flex w-100 align-center app-drag">
    <div
      class="tabs-container d-flex align-center app-no-drag"
      :style="{ 'max-width': `calc(100% - ${RIGHT_RESERVED_WIDTH}px)` }"
      @mouseout="tabWidthStore.handleMouseOut"
      @mouseover="tabWidthStore.handleMouseOver"
    >
      <!-- 普通标签页和分组混合渲染，外层加transition动画 -->
      <v-slide-y-reverse-transition group hide-on-leave origin="center top">
        <template v-for="item in tabStore.tabs" :key="item.id">
          <!-- 普通tab -->
          <TabItem v-if="item.type === 'tab'" v-bind="getTabItemProps(item)" />
          <!-- 分组 -->
          <TabGroupItem v-else-if="item.type === 'group'" :tab="item">
            <template #tab-item="{ tab }">
              <TabItem v-bind="getTabItemProps(tab)" class="tab-in-group" :group="item" />
            </template>
            <template #waiting-tab-item="{ tab }">
              <WaitingTabItem
                class="tab-in-group"
                :group="item"
                :tab="tab"
                :tab-width="tabWidthStore.tabWidth"
                @click="layoutStore.showGroupInspector(item.id)"
                @remove="onRemove(item, tab)"
              />
            </template>
          </TabGroupItem>
        </template>
      </v-slide-y-reverse-transition>
    </div>

    <v-divider class="ml-2 mr-1" inset vertical></v-divider>

    <div class="flex-none d-flex align-center">
      <AddTabBtn direction="top" />

      <v-btn class="app-no-drag" size="small" @click="addTwoTabs">添加两个</v-btn>
      <!--      <v-btn class="app-no-drag" size="small" @click="layoutStore.setTop(true)">setTop</v-btn>-->
    </div>

    <!-- 窗口控制按钮 -->
    <div class="window-controls d-flex align-center ml-auto app-no-drag">
      <v-defaults-provider
        :defaults="{
          VBtn: {
            color: '',
            variant: 'text',
            icon: true,
            class: 'window-control-btn'
          }
        }"
      >
        <v-btn data-testid="window-minimize-minimizeWindow" @click="minimizeWindow">
          <v-icon size="16">{{ mdiWindowMinimize }}</v-icon>
        </v-btn>
        <v-btn data-testid="window-maximize-toggleMaximize" @click="toggleMaximize">
          <v-icon size="16">{{ isMaximized ? mdiWindowRestore : mdiWindowMaximize }}</v-icon>
        </v-btn>
        <v-btn class="window-close-btn" data-testid="window-close-closeWindow" @click="closeWindow">
          <v-icon size="16">{{ mdiClose }}</v-icon>
        </v-btn>
      </v-defaults-provider>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue'
import AddTabBtn from '@/windows/layoutBrowser/components/common/AddTabBtn.vue'
import { useTabStore } from '@/windows/layoutBrowser/stores/tab'
import { RIGHT_RESERVED_WIDTH, useTabWidthStore } from '@/windows/layoutBrowser/stores/tabWidth'
import TabGroupItem from './TabGroup.vue'
import TabItem from './TabItem.vue'
import WaitingTabItem from './WaitingTabItem.vue'
import { mdiClose, mdiWindowMaximize, mdiWindowMinimize, mdiWindowRestore } from '@mdi/js'
import { openGroupNewTab } from '@/utils/tab-group'
import { useLayoutStore } from '@/windows/layoutBrowser/stores/layout'
import { layoutOn } from '@/utils/layoutEvent'
const layoutStore = useLayoutStore()

// ==================== 状态管理 ====================
const tabStore = useTabStore()
const tabWidthStore = useTabWidthStore()

// ==================== 窗口控制状态 ====================
const isMaximized = ref(false)

// ==================== 标签页操作 ====================
/**
 * 设置活动标签页
 */
function setActiveTab(id: number) {
  if (tabStore.activeTabId !== id) {
    tabStore.setActiveTab(id)
  }
}

function onRemove(group: F2.tab.Group, tab: F2.tab.CreateWithId) {
  group.waitingTabs = group.waitingTabs.filter(t => t.id !== tab.id)
  // 移除后，尝试打开其他等待的标签页
  if (group.waitingTabs.length > 0) {
    openGroupNewTab(group)
  }
}

// 生成 TabItem 通用属性
function getTabItemProps(tab: F2.tab.Entity) {
  return {
    tab,
    tabWidth: tabWidthStore.tabWidth,
    isActive: tab.id === tabStore.activeTabId,
    class: ['tab-item-class'],
    onMousedown: (e: MouseEvent) => {
      // 防止右键拖拽
      if (e.button !== 0) return
      setActiveTab(tab.id)
    }
  }
}

// ==================== 标签页创建 ====================

/**
 * 添加多个测试标签页
 */
function addTwoTabs() {
  _pre_.browser.createGroup([
    'https://www.baidu.com',
    'https://www.google.com',
    'https://en.as.com/',
    'https://en.as.com/soccer/',
    'https://en.as.com/news/real-madrid/',
    'https://en.as.com/news/liga-espanola-de-futbol/',
    'https://en.as.com/nba/',
    'https://www.youtube.com/diarioas',
    'https://www.bing.com',
    'https://www.ask.com',
    'https://www.wish.com',
    'https://www.alibaba.com'
  ])
}

// ==================== 窗口控制 ====================
/**
 * 最小化窗口
 */
function minimizeWindow() {
  _pre_.browser.minimizeWindow()
}

/**
 * 切换最大化/还原窗口
 */
function toggleMaximize() {
  if (isMaximized.value) {
    _pre_.browser.unmaximizeWindow()
  } else {
    _pre_.browser.maximizeWindow()
  }
}

/**
 * 关闭窗口
 */
function closeWindow() {
  _pre_.browser.closeWindow()
}

// 监听窗口最大化状态变化
let unsubscribe: (() => void) | undefined

onMounted(() => {
  // 获取初始最大化状态
  isMaximized.value = _pre_.browser.isWindowMaximized()

  // 监听状态变化
  unsubscribe = layoutOn('window:maximize-state', (maximized: boolean) => {
    isMaximized.value = maximized
  })
})

onUnmounted(() => {
  if (unsubscribe) {
    unsubscribe()
  }
})
</script>

<style scoped>
/* ==================== 标签容器样式 ==================== */
.tabs-container {
  flex: 0 1 auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
  transition: all 0.2s ease-in-out;
  position: relative; /* 为绝对定位的指示器提供参考点 */
}

.tabs-container::-webkit-scrollbar {
  display: none;
}

.tab-bbar {
  height: 35px;
  padding-top: 5px;
  background: rgba(var(--v-theme-tab-base), 1);
}

/* ==================== 窗口控制按钮样式 ==================== */
.window-controls {
  height: 100%;
  margin-right: 0;
  align-self: flex-start;
  margin-top: -1px; /* 抵消 tab-bbar 的 padding-top */
}

.window-control-btn {
  border-radius: 0 !important;
  transition: background-color 0.2s ease;
  min-width: 45px;
}

.window-control-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.window-close-btn:hover {
  background-color: #e81123;
  color: white;
}

.window-close-btn:hover :deep(.v-icon) {
  color: white !important;
}
</style>
